import {Component, Input, OnInit, ViewChild, DoCheck } from '@angular/core';
import {ModalDirective} from 'ngx-bootstrap';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../config/api';
import {HttpService} from '../../lib/service/http.service';
import {AdOssUploadService} from '../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../lib/service/local-storage.service';
import {Router} from '@angular/router';
import {AddressService} from '../../lib/service/address.service';

export class AccountInfo {
  nick_name: string;
  sex: string;
  address_code: string;
  address_code_explain: string;
  address_detail: string;
  avatar;
}

export class AccountExtend {
  company_name: string;  // 公司名称
  company_address_code: string;
  company_address_detail: string;
  contacts: string;
  contacts_mobile: number;
  contacts_wechat: string;
  contacts_qq: number;
  contacts_email;
  class;
}

export class PasswordInfo {
  old_password: string;
  new_password: string;
  again_password: string;
}



@Component({
  selector: 'app-main-header',
  templateUrl: './main-header.component.html',
  styleUrls: ['./main-header.component.scss'],
  providers: [
    LocalStorageService, AddressService
  ]
})
export class MainHeaderComponent implements OnInit, DoCheck {

  type: string;
  message: string;
  isShow = false;
  img_file: any;
  img_name: string;
  img_url: string;

  aliyunOssOutputUrl = AliyunOssOutputUrl;
  head_img: string;
  provinceList = [];
  cityList = [];
  regionList = [];
  provinceCode = 0;  // 选中省code
  cityCode = 0;
  regionCode = 0;
  provinceName: string;
  cityName: string;
  regionName: string;
  hadLoginName;
  appletName;
  authorizetion_status = false;
  publish_status = false;
  hasGetStatus = false;
  hasChangedImg = false;
  modifiedType = 'account';  // 修改账户的类型
  accountClass = [];
  firClass = [];
  secClass = [];
  fir: any = 0;
  sec: any = 0;
  accountInfo = new AccountInfo();
  passwordInfo = new PasswordInfo();
  accountExtend = new AccountExtend();
  canClick = true;

  @Input() hasHeaderAdditional;

  @ViewChild('personModal') public personModal: ModalDirective;

  constructor(private httpService: HttpService,
              private router: Router,
              private localStorageService: LocalStorageService,
              private addressService: AddressService,
              private adOssUploadService: AdOssUploadService) {
  }

  ngOnInit() {
    this.head_img = this.localStorageService.getUserInfo().avatar;
    this.hadLoginName = this.localStorageService.getUserInfo().nick_name;
  }

  ngDoCheck() {
    if (this.hasHeaderAdditional) {
      this.appletName = this.localStorageService.getNowApplet().title;
    }
  }

  // 获取当前小程序的状态
  getAuthStatus() {
    const authorization = this.localStorageService.getNowApplet();
    if (authorization && !this.hasGetStatus) {
      if (authorization.status === '未授权') {
        this.authorizetion_status = false;
        this.publish_status = false;
      } else if (authorization.status === '未发布') {
        this.authorizetion_status = true;
        this.publish_status = false;
      } else {
        this.authorizetion_status = true;
        this.publish_status = true;
      }
    }
  }

  clear() {
    this.localStorageService.clearAll();
    location.href = '/';
  }

  accountDlg() {
    if (!this.localStorageService.getNowApplet()) {return;}
    const userInfo = this.localStorageService.getUserInfo();
    this.accountInfo.nick_name = userInfo.nick_name;
    this.accountInfo.sex = userInfo.sex;
    this.accountInfo.avatar = userInfo.avatar;
    // this.accountInfo.address_code = userInfo.address_code;
    // this.accountInfo.address_code_explain = userInfo.address_code_explain;
    // this.accountInfo.address_detail = userInfo.address_detail;
    if (!!userInfo.avatar) {
      this.img_url = AliyunOssOutputUrl + '/' + userInfo.avatar;
    }
    // this.getAddressDetail(userInfo.address_code);
    this.getAccountExtend();
    // this.personModal.show();
    this.router.navigate(['/member/account/user']);
  }

  // 上传图片
  uploadImg($event: any) {
    this.hasChangedImg = true;

    const file = $event.path[0].files[0];
    const myReader = new FileReader();
    const self = this;
    this.img_file = file;

    myReader.readAsDataURL(file);
    myReader.onloadend = function (e) {
      self.img_url = myReader.result;
    };

    const suffix = file.name.replace(/.+\./, '').toLowerCase();
    const now = new Date();
    this.img_name = now.getTime() + '.' + suffix;
  }

  // 获取用户详情
  getUserInfo() {
    const url = `${adSystemApiUrl}/v1/member/account/user_infomation`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.localStorageService.setUserInfo(res.data);
          this.hadLoginName = this.localStorageService.getUserInfo().nick_name;
          this.head_img = this.localStorageService.getUserInfo().avatar;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 获取用户拓展信息
  getAccountExtend() {
    const url = `${adSystemApiUrl}/v1/member/account/getAccountExtend`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.accountExtend.company_name = res.data.company_name;
          this.accountExtend.company_address_code = res.data.company_address_code;
          this.accountExtend.company_address_detail = res.data.company_address_detail;
          this.accountExtend.contacts = res.data.contacts;
          this.accountExtend.contacts_mobile = res.data.contacts_mobile;
          this.accountExtend.contacts_email = res.data.contacts_email;
          this.getAddressDetail(this.accountExtend.company_address_code);
          this.getAllClass(0, 'firClass');
          if (!!res.data.class.length) {
            this.accountClass = [];
            res.data.class.every((val, idx, array) => {
              this.accountClass.push({firId: val.frist_class.id,secId: val.second_class.id,firName: val.frist_class.class_name,secName: val.second_class.class_name});
              return true;
            });
          }
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    )
  }

  // 获取用户分类扩展信息
  getAllClass(parent, container) {
    let parent_id;
    if (!parent) {
      parent_id = 0;
    } else {
      const idx = parent.indexOf('&');
      parent_id = this.fir.substring(0,idx);
    }
    const url = `${adSystemApiUrl}/v1/member/account/getAllClass?parent_id=${parent_id}`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        this[container] = res.data;
      }
    )
  }

  // 添加服务类目
  addAccountClass() {
    if (!this.sec) {
      return;
    }
    if (this.accountClass.length === 5) {
      this.type = 'info';
      this.message = '服务类目最多只能添加五个';
      this.isShow = true;
      return;
    }
    const firIdx = this.fir.indexOf('&');
    const secIdx = this.sec.indexOf('&');
    let firId = this.fir.substring(0,firIdx),
        secId = this.sec.substring(0,secIdx),
        firName = this.fir.substring(firIdx+1),
        secName = this.sec.substring(secIdx+1);
   this.accountClass.push({firId: firId,secId: secId,firName: firName,secName: secName});
   this.fir = 0;
   this.sec = 0;
  }

  // 修改账户信息后提交
  accountEditSubmit() {
    this.accountExtend.company_address_code = this.regionCode + '';
    this.accountInfo.address_code_explain = this.provinceName + ' ' + this.cityName + ' ' + this.regionName;
    this.accountInfo.address_code = this.accountExtend.company_address_code;
    this.accountInfo.address_detail = this.accountExtend.company_address_detail;
    const arr = [];
    this.accountClass.every((val, idx, array) => {
      arr.push(val.secId);
      return true;
    });
    this.accountExtend.class = JSON.stringify(arr);
    if (!this.accountExtend.contacts_email) { delete this.accountExtend.contacts_email }
    const url = `${adSystemApiUrl}/v1/member/account/edit`;
    return this.httpService.httpPostAuth(url, this.accountInfo).subscribe(
      res => {
        if (res.code === 2000) {
          const url = `${adSystemApiUrl}/v1/member/account/editAccountExtend`;
          return this.httpService.httpPostAuth(url, this.accountExtend).subscribe(
            rs => {
              if (rs.code === 2000) {
                if (this.hasChangedImg) {
                  const id = this.localStorageService.getUserInfo().id;
                  this.adOssUploadService.getSignature('/v1/common/member_avatar/' + id + '?callback=true').subscribe(
                    res1 => {
                      this.adOssUploadService.fileUpload(this.img_file, res1.data, this.img_name, 'avatar').subscribe(
                        res2 => {
                          if (res2.status == 200) {
                            this.type = 'success';
                            this.message = '修改成功';
                            this.isShow = true;
                            this.personModal.hide();
                            this.getUserInfo();
                          } else {
                            this.type = 'error';
                            this.message = '头像上传失败';
                            this.isShow = true;
                          }
                        }
                      );
                    }
                  );
                } else {
                  this.type = 'success';
                  this.message = '修改成功';
                  this.isShow = true;
                  this.personModal.hide();
                  this.getUserInfo();
                }
              }else {
                this.type = 'error';
                this.message = rs.message;
                this.isShow = true;
              }
            }
          )
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    )
  }

  // 修改账户密码后提交
  passwordEditSubmit() {
    this.canClick = false;
    const url = `${adSystemApiUrl}/v1/member/account/reset_password`;
    return this.httpService.httpPostAuth(url, this.passwordInfo).subscribe(
      res => {
        this.canClick = true;
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.personModal.hide();
          this.getUserInfo();
          this.passwordInfo.old_password = '';
          this.passwordInfo.new_password = '';
          this.passwordInfo.again_password = '';
        } else {
          if (!!res.data) {
            this.type = 'error';
            this.message = res.data.again_password[0];
            this.isShow = true;
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      }
    )
  }

  getAddressDetail(code) {
    if (!!code) {
      this.addressService.getAddressDetail(code).subscribe(
        res => {
          if (res.data) {
            if (res.data.province) {
              this.provinceCode = res.data.province.code;
              this.provinceName = res.data.province.name;
              this.getCityList(res.data.province.code);
            }
            if (res.data.city) {
              this.cityCode = res.data.city.code;
              this.cityName = res.data.city.name;
              this.getRegionList(res.data.city.code);
            }
            if (res.data.region) {
              this.regionName = res.data.region.name;
              this.regionCode = res.data.region.code;
            }
          }
          this.getProvinceList();
        }
      );
    } else {
      this.getProvinceList();
    }

  }

  getProvinceList() {
    this.addressService.getProvinceList().subscribe(
      res => {
        if (res.code === 2000) {
          this.provinceList = res.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  getCityList(provinceCode) {
    this.addressService.getCityList(provinceCode).subscribe(
      res => {
        if (res.code === 2000) {
          this.cityList = res.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  getRegionList(cityCode) {
    this.addressService.getRegionList(cityCode).subscribe(
      res => {
        if (res.code === 2000) {
          this.regionList = res.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 选择省之后
  changeProvince() {
    this.cityCode = 0;
    this.regionCode = 0;
    this.regionList = [];
    this.provinceList.every((val, idx, array) => {
      if (val.code == this.provinceCode) {
        this.provinceName = val.name;
        return false;
      }
      return true;
    });
    this.addressService.getCityList(this.provinceCode).subscribe(
      res => {
        if (res.code === 2000) {
          this.cityList = res.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 选择市之后
  changeCity() {
    this.regionCode = 0;
    this.cityList.every((val, idx, array) => {
      if (val.code == this.cityCode) {
        this.cityName = val.name;
        return false;
      }
      return true;
    });
    this.addressService.getRegionList(this.cityCode).subscribe(
      res => {
        if (res.code === 2000) {
          this.regionList = res.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 选择区之后
  changeRegion() {
    this.regionList.every((val, idx, array) => {
      if (val.code == this.regionCode) {
        this.regionName = val.name;
        return false;
      }
      return true;
    });
  }
}
